import cv2
import numpy as np

# 初始化变量
center_point = None
rect_points = None
outer = None
inner = None
#初始化摄像头
def laser_point():
    camera = cv2.VideoCapture(0)

    #设置摄像头分辨率
    camera.set(cv2.CAP_PROP_FRAME_WIDTH, 320)
    camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 240)

    camera.set(cv2.CAP_PROP_FPS, 30)
    # 检查摄像头是否成功打开
    if not camera.isOpened():
        print("无法打开摄像头")
        exit()
    while True:
        #读取摄像头帧
        ret, frame = camera.read()
        if not ret:
            print("无法从摄像头读取数据")
            break
        # 转换为 HSV 色彩空间
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        # 白色的 HSV 范围（可根据滑动条调整）
        lower_white = np.array([0, 0, 245])
        upper_white = np.array([179,10 , 255])
        mask2 = cv2.inRange(hsv, lower_white, upper_white)
        # 图像增强
        mask2 = cv2.GaussianBlur(mask2, (5, 5), 0)  # 高斯模糊
        kernel = np.ones((5, 5), np.uint8)
        # 开运算
        mask2 = cv2.morphologyEx(mask2, cv2.MORPH_OPEN, kernel)
        # 查找轮廓
        _ ,contours, _ = cv2.findContours(mask2, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        laser_detected = False

        for contour in contours:
            # 筛选面积较小的轮廓
            if 5<cv2.contourArea(contour) < 20:
                continue

            # 获取轮廓的边界框
            x, y, w, h = cv2.boundingRect(contour)

            # 计算轮廓的中心点
            center_x = x + w // 2
            center_y = y + h // 2
            center_point = (center_x, center_y)
            return center_point

            laser_detected = True

        if not laser_detected:
            cv2.putText(frame, "Laser not detected", (10, 30),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
        # 显示视频画面
        cv2.imshow('Laser Detection', frame)
        # 退出按键（按 'q' 键退出）
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    # 释放摄像头资源
    camera.release()
    # 关闭所有 OpenCV 窗口
    cv2.destroyAllWindows()